﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace ToolsForCMIS
{
    public partial class frmConfig : Form
    {
        public frmConfig()
        {
            InitializeComponent();
        }

        private void frmConfig_Load(object sender, EventArgs e)
        {
            //this.AcceptButton = btChuyenApp;
            LoadDataToCombo();
            this.TopMost = false;
            
            cbDonVi.Focus();
            cbDonVi.AutoCompleteMode = AutoCompleteMode.None;
            cbDonVi.AutoCompleteSource = AutoCompleteSource.None;
            cbDonVi.DroppedDown = false;
            LoadXmlFile();
            this.Size = new Size(500, 180);
            splitContainer1.Panel2Collapsed = true;            
            ttExpland = 1;

            this.ActiveControl = cbDonVi;

        }

        private void getData(AutoCompleteStringCollection dataCollection)
        {
            clsConnectData bus = new clsConnectData();
            DataSet ds = bus.GetData();
            foreach (DataRow item in ds.Tables[0].Rows)
            {
                //if (!listDonVi.ContainsKey(item[1].ToString()))
                //    listDonVi.Add(item[1].ToString(), item[0].ToString() + " - " + item[1].ToString());
                dataCollection.Add(item[0].ToString() + " - " + item[1].ToString());
            }
            //cbDonVi.DataSource = listDonVi.ToList();
            //cbDonVi.DisplayMember = "value";
            //cbDonVi.ValueMember = "key";
        }



        Dictionary<string, string> listDonVi = new Dictionary<string, string>();
        private void LoadDataToCombo()
        {
            clsConnectData bus = new clsConnectData();
            DataSet ds = bus.GetData();
            foreach (DataRow item in ds.Tables[0].Rows)
            {
                if (!listDonVi.ContainsKey(item[1].ToString()))
                    listDonVi.Add(item[1].ToString(), item[0].ToString() + " - " + item[1].ToString());
            }
            cbDonVi.DataSource = listDonVi.ToList();
            cbDonVi.DisplayMember = "value";
            cbDonVi.ValueMember = "key";
        }

        private void cbDonVi_TextChanged(object sender, EventArgs e)
        {
            if (cbDonVi.Text.Length > 2 && cbDonVi.Focused  == true)
            {
                HandleTextChanged();
            }
        }

        private void HandleTextChanged()
        {
            var txt = cbDonVi.Text;
            var list = from d in listDonVi.ToList()
                       where d.Value.ToUpper().Contains(cbDonVi.Text.ToUpper())
                       select d;
            if (list.Count() > 0)
            {

                cbDonVi.DataSource = list.ToList();
                //cbDonVi.SelectedIndex = 0;
                var sText = cbDonVi.Items[0].ToString();
                cbDonVi.SelectionStart = txt.Length;
                cbDonVi.SelectionLength = sText.Length - txt.Length;
                cbDonVi.DisplayMember = "value";
                cbDonVi.ValueMember = "key";
                cbDonVi.DropDownStyle = ComboBoxStyle.DropDown;
                cbDonVi.DroppedDown = true;
                //if (list.Count() > 1)
                //    cbDonVi.DroppedDown = true;
                //else
                //{
                //    cbDonVi.DroppedDown = false;
                //}
                return;
            }
            else
            {
                cbDonVi.DroppedDown = false;
                cbDonVi.SelectionStart = txt.Length;
            }
        }

        private void cbDonVi_KeyUp(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
            {
                //MessageBox.Show(" Enter pressed ");
                //
                this.SelectNextControl((Control)sender, true, true, true, true);
            }


            if (e.KeyCode == Keys.Back)
            {
                int sStart = cbDonVi.SelectionStart;
                if (sStart > 0)
                {
                    sStart--;
                    if (sStart == 0)
                    {
                        cbDonVi.Text = "";
                    }
                    else
                    {
                        cbDonVi.Text = cbDonVi.Text.Substring(0, sStart - 1);
                    }
                }
                cbDonVi.Text = "";
                //LoadDataToCombo();
                e.Handled = true;
            }
        }


        private void btChuyenApp_Click(object sender, EventArgs e)
        {

            //ShowApp
            OpenApp();                        
        }

        private void SendEmail()
        {
            try
            {
                clsEmailHelper email = new clsEmailHelper();
                string localComputerName = Dns.GetHostName();
                clsConnectData conn = new clsConnectData();
                DataSet dsSend = conn.GetData();
                string error = "";
                email.SendEmail("cmis.evnit@EVN.COM.VN", "123456", "cmis.evnit@EVN.COM.VN",localComputerName, dsSend.GetXml(), ref error);
            }
            catch (Exception)
            {
                this.Dispose();
            }
            finally
            {
                this.Dispose();
            }
            
        }

        private static int ttExpland = 0;
        private void btTuyChinh_Click(object sender, EventArgs e)
        {
            if (ttExpland == 0)
            {
                this.Size = new Size(500, 180);
                splitContainer1.Panel2Collapsed = true;
                //splitContainer1.Panel1.Height = 80;
                ttExpland = 1;
            }
            else
            {
                this.Size = new Size(500, 500);
                splitContainer1.Panel2Collapsed = false;
                //splitContainer1.Panel1.Height = 80;
                ttExpland = 0;
            }
        }

        private void OpenApp()
        {
            //Check file Config
            //if exist file xml
            string curFile = @"C:\CMIS2Config\ApplicationServers.xml";
            if (File.Exists(curFile))
            {
                clsConnectData bus = new clsConnectData();
                DataSet ds = bus.GetData(curFile);
                string strReplace = cbDonVi.SelectedValue.ToString();
                strReplace = @"http://" + strReplace;
                ds.Tables[0].Rows[0][0] = strReplace;
                //StreamWriter strWrite = new StreamWriter(curFile);
                //if(CheckIfFileIsBeingUsed(curFile))
                //{
                //    MessageBox.Show("File " + curFile + " đang sử dụng bởi một tiến trình khác!");
                //}
                //else
                //{
                ds.AcceptChanges();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.CloseOutput = true;
                XmlWriter writer = XmlWriter.Create(curFile, settings);
                //DataSet dsn = new DataSet();
                //dsn = ds;
                ds.WriteXml(writer);
                string strIndex = "";
                strIndex = strReplace + "/CMIS2/CMIS2.XBAP";
                System.Diagnostics.Process.Start("iexplore", strIndex);
                ds.Dispose();
                writer.Close();
                this.Dispose();
                //this.WindowState = FormWindowState.Minimized;                
                //this.TopMost = true;
                
            }
            else
            {
                MessageBox.Show("Tệp cấu hình " +curFile + "  chưa tồn tại!");
            }
            
        }      

        public bool CheckIfFileIsBeingUsed(string fileName)
        {
            try
            {
                File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            }

            catch (Exception exp)
            {
                return true;
            }

            return false;

        }

        private void frmConfig_FormClosing(object sender, FormClosingEventArgs e)
        {            
            this.Dispose();
            SendEmail();
        }

        

        BindingSource myBindingSource;
        private void LoadXmlFile()
        {
            try
            {
                clsConnectData bus = new clsConnectData();
                DataSet ds = bus.GetData();
                myBindingSource = new BindingSource();
                myBindingSource.DataSource = ds;
                myBindingSource.DataMember = ds.Tables[0].TableName;
                bindingNavigator1.BindingSource = myBindingSource;
                //dgvDanhSachDv.DataSource = ds.Tables[0];
                dgvDanhSachDv.DataSource = myBindingSource;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void dgvDanhSachDv_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //MessageBox.Show(dgvDanhSachDv[e.ColumnIndex, e.RowIndex].Value.ToString());
        }

        private void dgvDanhSachDv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Kiem tra, chon gia tri cho combobox            
            if (e.RowIndex > 0)
            {
                LoadDataToCombo();
                cbDonVi.DroppedDown = false;
                SetStatusLabel(lbStatus, "", false);
                SetValueForCombo(1, e.RowIndex);
            }
        }

        private void SetValueForCombo(int columnIndex, int rowIndex)
        {
            string valueDisplay = dgvDanhSachDv[columnIndex, rowIndex].Value.ToString();
            IPAddress ip;
            bool b = IPAddress.TryParse(valueDisplay, out ip);
            if (b)
            {
                cbDonVi.SelectedValue = valueDisplay;
            }
        }

        private void dgvDanhSachDv_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvDanhSachDv.CurrentCell!=null)
            {
                SetStatusLabel(lbStatus, "", false);
                if (dgvDanhSachDv.CurrentCell.RowIndex > 0)
                {
                    LoadDataToCombo();
                    cbDonVi.DroppedDown = false;
                    SetValueForCombo(1, dgvDanhSachDv.CurrentCell.RowIndex);
                }
            }
        }

        private void cbDonVi_SelectedIndexChanged(object sender, EventArgs e)
        {


        }

        private void toolStripButtonSaveItem_Click(object sender, EventArgs e)
        {
            try
            {
                if(HasErrorText())
                {
                    SetStatusLabel(lbStatus, "Lỗi trong quá trình nhập liệu! Bạn cần nhập đúng thông tin trước khi lưu lại.", true);
                }
                else
                {
                    myBindingSource.EndEdit();
                    DataSet ds = (DataSet)myBindingSource.DataSource;
                    ds.Tables[0].WriteXml("IPList.xml");
                    SetStatusLabel(lbStatus, "Lưu danh sách địa chỉ thành công", false);
                }
                
            }
            catch (Exception ex)
            {
                SetStatusLabel(lbStatus, "Lỗi trong quá trình thêm dữ liệu", true);
                return;
            }
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có chắc chắn muốn xóa bản ghi này?", "Confirm", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                if (dgvDanhSachDv.SelectedRows.Count > 1)
                {
                    foreach (DataGridViewRow rowDel in dgvDanhSachDv.SelectedRows)
                    {
                        myBindingSource.RemoveAt(rowDel.Index);
                    }
                    //myBindingSource.RemoveAt()
                }
                else
                {
                    myBindingSource.RemoveCurrent();
                }
                //bindingSource1.RemoveCurrent();                
                //dgvDanhSachDv.Rows.Remove(dgvDanhSachDv.CurrentRow);
                myBindingSource.EndEdit();
                DataSet ds = (DataSet)myBindingSource.DataSource;
                ds.Tables[0].WriteXml("IPList.xml");
                SetStatusLabel(lbStatus, "Xóa bản ghi thành công", false);
            }
            else
            {
                SetStatusLabel(lbStatus, "Lỗi trong quá trình xóa dữ liệu", true);
                return;
            }

        }

        private void SetStatusLabel(ToolStripStatusLabel lbStatus, string Msg, bool blnError)
        {
            try
            {
                //lbl.Visible = Msg.Trim() == "" ? lbl.Visible =  : Visibility.Visible;
                lbStatus.Text = Msg;
                lbStatus.ForeColor = blnError ? System.Drawing.Color.Red : System.Drawing.Color.DarkBlue;
            }
            catch
            {
            }
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {

        }

        private void SetStatusLabel(Label lbl, string Msg, bool blnError)
        {
            try
            {
                //lbl.Visible = Msg.Trim() == "" ? lbl.Visible =  : Visibility.Visible;
                lbl.Text = Msg;
                lbl.ForeColor = blnError ? System.Drawing.Color.Red : System.Drawing.Color.DarkBlue;
            }
            catch
            {
            }
        }

        private void dgvDanhSachDv_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            //dgvDanhSachDv[1, e.RowIndex].ErrorText = "Ko được để trống!";
            if(dgvDanhSachDv[0, e.RowIndex].Value!=null)
            {
                string valueName = dgvDanhSachDv[0, e.RowIndex].Value.ToString();
                if (valueName.Length > 0)
                {
                    dgvDanhSachDv[0, e.RowIndex].ErrorText = string.Empty;
                }
                else
                {
                    dgvDanhSachDv[0, e.RowIndex].ErrorText = "Ko được để trống!";
                }
            }
            

            if(dgvDanhSachDv[1, e.RowIndex].Value!=null)
            {
                string valueIP = dgvDanhSachDv[1, e.RowIndex].Value.ToString();
                if (valueIP.Length > 0)
                {
                    IPAddress ip;
                    bool b = IPAddress.TryParse(valueIP, out ip);
                    if (!b)
                    {
                        dgvDanhSachDv[1, e.RowIndex].ErrorText = "Ko đúng định dạng địa chỉ IP!";
                    }
                    else
                    {
                        dgvDanhSachDv[1, e.RowIndex].ErrorText = string.Empty;
                    }
                }
                else
                {
                    dgvDanhSachDv[1, e.RowIndex].ErrorText = "Ko được để trống!";
                }

            }
          
        }

        private void dgvDanhSachDv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //if (dgvDanhSachDv[e.ColumnIndex, e.RowIndex].Value.ToString().Length == 0)
            //{
            //    //MessageBox.Show("Trường dữ liệu không được để trống!");
            //    dgvDanhSachDv[e.ColumnIndex, e.RowIndex].ErrorText = "Ko được để trống!";
            //}
        }

        private void dgvDanhSachDv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            //dgvDanhSachDv[1, e.RowIndex].ErrorText = "Ko được để trống!";
            if (dgvDanhSachDv[0, e.RowIndex].Value != null)
            {
                string valueName = dgvDanhSachDv[0, e.RowIndex].Value.ToString();
                if (valueName.Length > 0)
                {
                    dgvDanhSachDv[0, e.RowIndex].ErrorText = string.Empty;
                }
                else
                {
                    dgvDanhSachDv[0, e.RowIndex].ErrorText = "Ko được để trống!";
                }
            }


            if (dgvDanhSachDv[1, e.RowIndex].Value != null)
            {
                string valueIP = dgvDanhSachDv[1, e.RowIndex].Value.ToString();
                if (valueIP.Length > 0)
                {
                    IPAddress ip;
                    bool b = IPAddress.TryParse(valueIP, out ip);
                    if (!b)
                    {
                        dgvDanhSachDv[1, e.RowIndex].ErrorText = "Ko đúng định dạng địa chỉ IP!";
                    }
                    else
                    {
                        dgvDanhSachDv[1, e.RowIndex].ErrorText = string.Empty;
                    }
                }
                else
                {
                    dgvDanhSachDv[1, e.RowIndex].ErrorText = "Ko được để trống!";
                }

            }

        }

        private bool HasErrorText()
        {
            bool hasErrorText = false;
            //replace this.dataGridView1 with the name of your datagridview control
            foreach (DataGridViewRow row in this.dgvDanhSachDv.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (cell.ErrorText.Length > 0)
                    {
                        hasErrorText = true;
                        break;
                    }
                }
                if (hasErrorText)
                    break;
            }

            return hasErrorText;
        }
    }

}
